﻿namespace DeltaGroup.WheelOfJeopardy.Util
{
    using System;
    using System.Collections.Generic;
    using System.Windows;
    using System.Windows.Media;

    public static class Extensions
    {
        #region Methods

        /// <summary>
        /// Shuffles the specified list.
        /// </summary>
        /// <typeparam name="TE">The type of the E.</typeparam>
        /// <param name="list">The list.</param>
        /// <returns></returns>
        public static List<TE> Shuffle<TE>(this List<TE> list)
        {
            // so we dont remove from original
            var temp = new List<TE>(list); 

            var result = new List<TE>();

            var r = new Random();
            while (temp.Count > 0)
            {
                var randomIndex = r.Next(0, temp.Count);
                result.Add(temp[randomIndex]);

                //remove to avoid duplicates
                temp.RemoveAt(randomIndex); 
            }
            return result;
        }

        /// <summary>
        /// Toes the int.
        /// </summary>
        /// <param name="s">The s.</param>
        /// <returns></returns>
        public static int ToInt(this string s)
        {
            int i;
            return int.TryParse(s, out i) ? i : 0;
        }

        /// <summary>
        /// Finds the visual child.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="depObj">The dep obj.</param>
        /// <returns></returns>
        public static T FindVisualChild<T>(DependencyObject depObj)
            where T : DependencyObject
        {
            if (depObj != null)
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                    if (child != null && child is T)
                    {
                        return (T)child;
                    }

                    T childItem = FindVisualChild<T>(child);
                    if (childItem != null) return childItem;
                }
            }
            return null;
        }

        #endregion Methods
    }
}